package com.hssoftvn.android.apps.tinycouplechat;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.Socket;

import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;

import android.content.Context;
import android.net.ConnectivityManager;
import android.net.wifi.WifiManager;
import android.os.Handler;

/* SERVER INFORMATION
 * http://members.000webhost.com/index.php?
 * Username: huynhhoangson@gmail.com
 * Password: ...told..02
 * Server URL: http://tinycouplechat.hssoftvn.comlu.com/
 * DATABASE
 * $mysql_host = "mysql12.000webhost.com";
 * $mysql_database = "a2793001_couple";
 * $mysql_user = "a2793001_tiny";
 * $mysql_password = "sonmi860302";
 * table Users
 * 		Create new user: 
 * 		$sql = 'INSERT INTO `a2793001_couple`.`users` (`id`, `name`, `sex`, `dob`, `avatar`) VALUES (\'01685531924\', \'tiny\', \'Male\', NULL, NULL);';
 * 		Select an user info:
 * 		$sql = 'SELECT * FROM `users` WHERE id=\'01685531924\'';
 * 		Update user infor
 * 		$sql = 'UPDATE `a2793001_couple`.`users` SET `avatar` = \'x\' WHERE CONVERT(`users`.`id` USING utf8) = \'0972993771\' AND CONVERT(`users`.`name` USING utf8) = \'Red\' AND CONVERT(`users`.`sex` USING utf8) = \'Male\' AND `users`.`dob` IS NULL AND CONVERT(`users`.`avatar` USING utf8) IS NULL LIMIT 1;';
 * Table usersonlinestatus
 * 		Insert a status
 * 		$sql = 'INSERT INTO `a2793001_couple`.`usersonlinestatus` (`uid`, `isonline`, `lastonline`, `lastloc`) VALUES (\'01685531924\', \'Yes\', \'\', NULL);'; * 
 * 		Select a status from an user
 * 		$sql = 'SELECT * FROM `usersonlinestatus` WHERE uid=\'01685531924\'';
 * 		Update status
 * 		$sql = 'UPDATE `a2793001_couple`.`usersonlinestatus` SET `lastloc` = \'last location\' WHERE CONVERT(`usersonlinestatus`.`uid` USING utf8) = \'01685531924\' AND CONVERT(`usersonlinestatus`.`isonline` USING utf8) = \'Yes\' AND `usersonlinestatus`.`lastonline` = \'0000-00-00 00:00:00\' AND CONVERT(`usersonlinestatus`.`lastloc` USING utf8) IS NULL LIMIT 1;';
 */

public class NetworkHelper {

	public static String HOST_URL = "http://couplechat.hssoftvn.url.ph";
	//public static String URL_SENDING_MSG = "http://tinycouplechat.hssoftvn.comlu.com/process.php";
	public static String URL_SENDING_MSG = 
			"http://couplechat.hssoftvn.url.ph?action=sendmsg&fromid=@FROMID&toid=@TOID&message=@MESSAGE&sentTime=@SENTTIME&status=@STATUS&location=@LOCATION";
	public static String URL_CHECKING_INCOMING_MSG = 
			"http://couplechat.hssoftvn.url.ph?action=checkmsg&toid=@TOID&status=@STATUS";
	public static String URL_CHECKING_MESSAGE_STATUS = 
			"http://couplechat.hssoftvn.url.ph?action=checkmsgstatus&mid=@MSG_ID";
	public static String URL_UPDATE_MESSAGE_STATUS = 
			"http://couplechat.hssoftvn.url.ph?action=updatemsgstatus&mid=@MSG_ID&status=@STATUS&statusTime=@STATUSTIME";
			
	public static String URL_ADD_USER_INFO = 
			"http://couplechat.hssoftvn.url.ph?action=adduser&username=@USERNAME&password=@PASSWORD&email=@EMAIL&dob=@DOB&avatar=@AVATAR&status=@STATUS&lastOnlineTime=@LASTONLINETIME&lastLocation=@LASTLOCATION";
	public static String URL_UPDATE_USER_INFO = 			"http://couplechat.hssoftvn.url.ph?action=getuserinfo&username=@USERNAME&password=@PASSWORD&email=@EMAIL&dob=@DOB&avatar=@AVATAR&status=@STATUS&lastOnlineTime=@LASTONLINETIME&lastLocation=@LASTLOCATION";
	public static String URL_GET_USER_INFO = 
			"http://couplechat.hssoftvn.url.ph?action=getuserinfo&username=@USERNAME";
	public static String URL_CHECKING_USER_ONLINE_STATUS = "http://couplechat.hssoftvn.url.ph/?action=checkonlinestatus&username=@USERNAME";
	
	public static String URL_UPDATE_USER_ONLINE_STATUS = "http://couplechat.hssoftvn.url.ph/?action=updateuserstatus&username=@USERNAME&status=@STATUS&lastOnlineTime=@LASTONLINETIME&lastLocation=@LASTLOCATION";
		
	public static int HOST_PORT = 8080;
	public static int CLIENT_PORT = 8899;
		
	public static final String ERROR_NO_ERRORS= "ok";
	public static final String ERROR_NO_CONNECTION = "noconnection";
	public static final String ERROR_TIMEOUT = "timeout";
	public static final String ERROR_SERVER_ISSUE = "server";
	public static final String ERROR_UNKNOWN = "unknown";

    static public String getHttpResponse(String RequestUrl)
    {
    	String response_text = null;
		BufferedReader stream_in = null;    	
		try
		{
			HttpClient client = new DefaultHttpClient();
			HttpGet request = new HttpGet(RequestUrl);
			HttpResponse response = client.execute(request);			
			stream_in = new BufferedReader (new InputStreamReader(response.getEntity().getContent()));
            StringBuffer buffer = new StringBuffer("");
            String line = "";
            while ((line = stream_in.readLine()) != null)
            {
            	buffer.append(line);
            }
            stream_in.close();
            response_text = buffer.toString();
            
            //tiny: trim some redundant text
            /*
            if (response_text.length()>10)
            {
            	int trimPos = response_text.indexOf("<!--");            
            	response_text = response_text.substring(0, trimPos);
            }
            */
            
		} catch (Exception e) {			
			response_text = e.getMessage();
		}
		finally 
		{
            if (stream_in != null) 
            {
                try 
                {
                	stream_in.close();
                } 
                catch (Exception e) {
                	response_text = e.getMessage();
                }
            }
		}
		
		return response_text;
    }

    /*
	 * Return error codes:
	 * - e|errorCode : NO_ERRORS, SERVER_ERROR, UNKNOWN
	 * - s|status: delivered, seen
	 */   
    public static String getSendingResponse(String response){

    	return "";
    }
    
    /*
	 * Return error codes:
	 * - e|errorCode : NO_ERRORS, SERVER_ERROR, UNKNOWN
	 * - f|FROM
	 * - m|MESSAGE
	 * - d|DATE SENT
	 */
    public static String getIncomingMsgResponse(String response){

    	return "";
    }
    
    /*
	 * Return error codes:
	 * - e|errorCode : NO_ERRORS, SERVER_ERROR, UNKNOWN
	 * - f|FROM
	 * - mid|MESSAGE ID
	 * - s|seen or unseen
	 */
    public static String getMsgSeenStatusResponse(String response){

    	return "";
    }
    
    public static boolean doesResponseHasError(String response){
    	
    	String error = ERROR_NO_ERRORS;
    	
    	//if (response.contains("</script") && response.contains("http://p.pw/404") )
    		error = ERROR_SERVER_ISSUE;
    	//If no errors, read the response from server
    	//if (!error.equalsIgnoreCase(ERROR_SERVER_ISSUE))
    	//{
    	//}
    	//return error.equalsIgnoreCase(ERROR_NO_ERRORS);

		return true;
    }
    
    static ConnectivityManager mConnectivityManager ;
    static WifiManager mWifiManager ;
	

	public static void Init()
	{
		mWifiManager = (WifiManager) Utils.getApplication().getSystemService(Context.WIFI_SERVICE); 			
		mConnectivityManager 	= (ConnectivityManager) Utils.getApplication().getSystemService(Context.CONNECTIVITY_SERVICE);
	}
	public static boolean isWifiAlive()
	{
		boolean check = false;
		if (mConnectivityManager != null && mConnectivityManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI) != null)
			check = mConnectivityManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI).isConnected();
		return mWifiManager.isWifiEnabled() && check;
	}
	
	public static ChatUser createNewUser()
	{
		Thread threadCreate = new Thread(new Runnable() {
			
			@Override
			public void run() {
				// TODO Auto-generated method stub
		    	
		    	String requests="";
		    	String responses="";
		    	
		    	try{
		    		
			    		//Init status
		    			/* http://couplechat.hssoftvn.url.ph?action=adduser&
		    				username=@USERNAME&
		    				password=@PASSWORD&
		    				email=@EMAIL&
		    				dob=@DOB&
		    				avatar=@AVATAR&
		    				status=@STATUS&
		    				lastOnlineTime=@LASTONLINETIME&
		    				lastLocation=@LASTLOCATION
		    			*/
			    		String url = NetworkHelper.URL_ADD_USER_INFO;
			    		url = url.replace("@USERNAME",Utils.getApplication().getMyInfo().mUsername);
			    		url = url.replace("@PASSWORD",Utils.getApplication().getMyInfo().mPassword);
			    		url = url.replace("@EMAIL",Utils.getApplication().getMyInfo().Email);
			    		url = url.replace("@DOB",Utils.getApplication().getMyInfo().DoB);
			    		url = url.replace("@AVATAR",Utils.getApplication().getMyInfo().mAvatar);
			    		url = url.replace("@STATUS",Utils.getApplication().getMyInfo().Status);
			    		url = url.replace("@LASTONLINETIME",Utils.getApplication().getMyInfo().LastOnlineTime);
			    		url = url.replace("@LASTLOCATION",Utils.getApplication().getMyInfo().LastLocation);
			    		
			    		responses = NetworkHelper.getHttpResponse(url);
			    		//successful
			    		if (responses.contains("|")){
			    			Utils.ShowToast("Account " + Utils.getApplication().getMyInfo().mUsername + " is created!\nEnjoy your chat!");
			    		}
			    		// failed
			    		else {
			    			Utils.ShowToast("Account " + Utils.getApplication().getMyInfo().mUsername + " is existed.\nPlease use another user id!");
			    			Utils.getApplication().getMyInfo().mUsername = "-1";
			    		}
		    	
		    	} catch(Exception ex){
		    		Utils.ShowToast("Server error. Please try later.");
		    		Utils.getApplication().getMyInfo().mUsername = "-1";
		    	}
			}
		});
		
		try{
			threadCreate.run();
		}catch(Exception ee){
			
		}
		
		return Utils.getApplication().getMyInfo();
	}
	
	public static boolean checkIfUserExisted(final String username)
	{
		Thread threadCreate = new Thread(new Runnable() {
			
			@Override
			public void run() {
				// TODO Auto-generated method stub
		    	
		    	String requests="";
		    	String responses="";
		    	
		    	try{
		    		
			    		//Init status
		    			/* http://couplechat.hssoftvn.url.ph?action=getuserinfo&username=@USERNAME
		    			*/
			    		String url = NetworkHelper.URL_GET_USER_INFO;
			    		url = url.replace("@USERNAME",username);
			    		responses = NetworkHelper.getHttpResponse(url);
			    		//successful
			    		if (responses.contains("|")){
			    		}
			    		// failed
			    		else {
			    			Utils.ShowToast("Account " + Utils.getApplication().getMyInfo().mUsername + " is existed.\nPlease use another user id!");
			    		}
		    	
		    	} catch(Exception ex){
		    		Utils.ShowToast("Server error. Please try later.");
		    		Utils.getApplication().getMyInfo().mUsername = "-1";
		    	}
			}
		});
		
		try{
			threadCreate.run();
		}catch(Exception ee){
			
		}
		
		return true;
	}
	
	
}
